let ws;

const wsState = {
	getState: 3,
	getMessage: undefined 
}

export default {
	wsState,
}
export function init() {
	//ws = new WebSocket('ws://192.168.1.177:9094/websocket/message');
	//ws = new WebSocket('ws://47.111.242.22:8080/ruoyi-admin/websocket/message');
	ws = new WebSocket('ws://192.168.1.149/dev-api/system/websocket/message');
	
	
	ws.onopen = function(evt) {
		console.log("Connection open ...");
		wsState.getState = 1;
		startHeartbeat();
		// ws.send("hey 你好");
	};

	ws.onmessage = function(evt) {
		// ws.close();
		let str = "";
		if(evt.data == "1"){
			str = "已连续观看一分钟，获得5积分";
		}else if(evt.data == "2"){
			str = "已连续观看五分钟，获得10积分";
		}else{
			str = "已连续观看十五分钟，获得15积分";
		}
		wsState.getMessage = str;
		console.log(evt)
	};

	ws.onclose = function(evt) {
		wsState.getState = 3;
		console.log("Connection closed.");
	};
}

export function sendData(data) {
	ws.send(data);
}


export function wsClose() {
	ws.close();
}


function startHeartbeat(){
	//let that = this;
	let object = window.setInterval(function() {
		console.log(ws.readyState)
		wsState.getState = ws.readyState
		if(ws.readyState == 1){
			
			sendData("heartbeat");
			console.log("heartbeat");
		}else{
			init();
			console.log("init")
		}
	}, 20000)
}